package com.xz.diagnosis.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xz.common.core.domain.model.LoginUser;
import com.xz.common.exception.ServiceException;
import com.xz.common.utils.DateUtils;
import com.xz.common.utils.RedisCode;
import com.xz.common.utils.SecurityUtils;
import com.xz.diagnosis.domain.DiagnosisItem;
import com.xz.diagnosis.domain.DiagnosisPackage;
import com.xz.diagnosis.domain.DiagnosisPackageItem;
import com.xz.diagnosis.dto.DiagnosisItemDto;
import com.xz.diagnosis.mapper.DiagnosisItemMapper;
import com.xz.diagnosis.mapper.DiagnosisPackageItemMapper;
import com.xz.diagnosis.mapper.DiagnosisPackageMapper;
import com.xz.diagnosis.service.IDiagnosisItemService;
import com.xz.diagnosis.vo.DiagnosisItemVo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.List;

/**
 * 诊疗项目Service业务层处理
 *
 * @author xz
 * @date 2024-03-14
 */
@Service
public class DiagnosisItemServiceImpl extends ServiceImpl<DiagnosisItemMapper, DiagnosisItem> implements IDiagnosisItemService {
  @Autowired
  private DiagnosisItemMapper diagnosisItemMapper;
  @Autowired
  private DiagnosisPackageMapper diagnosisPackageMapper;
  @Autowired
  private DiagnosisPackageItemMapper diagnosisPackageItemMapper;

  /**
   * 查询诊疗项目
   *
   * @param id 诊疗项目主键
   * @return 诊疗项目
   */
  @Override
  public DiagnosisItem selectDiagnosisItemById(Long id) {
    return diagnosisItemMapper.selectDiagnosisItemById(id);
  }

  /**
   * 查询诊疗项目列表
   *
   * @param diagnosisItem 诊疗项目
   * @return 诊疗项目
   */
  @Override
  public List<DiagnosisItem> selectDiagnosisItemList(DiagnosisItem diagnosisItem) {
    return diagnosisItemMapper.selectDiagnosisItemList(diagnosisItem);
  }
  /**
   * 查询诊疗项目列表
   *
   * @param diagnosisItem 诊疗项目
   * @return 诊疗项目
   */
  @Override
  public List<DiagnosisItemVo> selectDiagnosisItemVoList(DiagnosisItem diagnosisItem) {
    return diagnosisItemMapper.selectDiagnosisItemVoList(diagnosisItem);
  }

  /**
   * 新增诊疗项目
   *
   * @param dto 诊疗项目
   * @return 结果
   */
  @Override
  @Transactional(rollbackFor = Exception.class)
  public int insertDiagnosisItem(DiagnosisItemDto dto) {

    DiagnosisItem entity = new DiagnosisItem();
    BeanUtils.copyProperties(dto,entity);
    //编号
    entity.setItemNo(RedisCode.getCode("ZLXM"));
    //校验字段
    verifyFields(entity);
    //填充创建人信息
    LoginUser user = SecurityUtils.getLoginUser();
    entity.setCreateBy(user.getUserId());
    entity.setCreateTime(DateUtils.getNowDate());
    entity.setTenantId(user.getTenantId());
    entity.setDeptId(user.getDeptId());
    return diagnosisItemMapper.insertDiagnosisItem(entity);
  }

  /**
   * 修改诊疗项目
   *
   * @param dto 诊疗项目
   * @return 结果
   */
  @Override
  @Transactional(rollbackFor = Exception.class)
  public int updateDiagnosisItem(DiagnosisItemDto dto) {

    DiagnosisItem entity = baseMapper.selectById(dto.getId());
    if(null != entity){
      BeanUtils.copyProperties(dto,entity);
      //校验字段
      verifyFields(entity);
      //填充更新人信息
      LoginUser user = SecurityUtils.getLoginUser();
      entity.setUpdateBy(user.getUserId());
      entity.setUpdateTime(DateUtils.getNowDate());
      return diagnosisItemMapper.updateDiagnosisItem(entity);
    }
    return 0;
  }

  /**
   * 校验字段
   *
   * @param entity
   */
  private void verifyFields(DiagnosisItem entity) {

    // 校验名称唯一性
    LambdaQueryWrapper<DiagnosisItem> wrapper = Wrappers.lambdaQuery(DiagnosisItem.class);
    wrapper.eq(DiagnosisItem::getItemName, entity.getItemName());
    wrapper.ne(null != entity.getId(), DiagnosisItem::getId, entity.getId());
    wrapper.eq(DiagnosisItem::getDelFlag, 0);
    int count = diagnosisItemMapper.selectCount(wrapper);
    if (0 < count) {
      throw new ServiceException("该项目名称已存在");
    }
  }

  /**
   * 批量删除诊疗项目
   *
   * @param ids 需要删除的诊疗项目主键
   * @return 结果
   */
  @Override
  @Transactional(rollbackFor = Exception.class)
  public int deleteDiagnosisItemByIds(Long[] ids) {

    for (Long id : ids) {
      DiagnosisItem items = diagnosisItemMapper.selectById(id);
      if (null == items) {
        continue;
      }
      //查询给引用的id，
      LambdaQueryWrapper<DiagnosisPackageItem> wrapper = Wrappers.lambdaQuery(DiagnosisPackageItem.class);
      wrapper.select(DiagnosisPackageItem::getPackageId);
      wrapper.eq(DiagnosisPackageItem::getItemId, id);
      wrapper.eq(DiagnosisPackageItem::getDelFlag, 0);
      List<DiagnosisPackageItem> packageList = diagnosisPackageItemMapper.selectList(wrapper);
      //判断是否给引用，如果是则抛出异常，告诉前端要先于某个套餐内移除该项目。
      if (!CollectionUtils.isEmpty(packageList)) {
        DiagnosisPackage diagnosisPackage = diagnosisPackageMapper.selectById(packageList.get(0).getPackageId());
        throw new ServiceException("操作失败，该项目" + items.getItemName()
          + "正在被套餐" + diagnosisPackage.getPackageName() + "使用中，请先于套餐内移除该项目。");
      }
      //开始删除。
      diagnosisItemMapper.deleteDiagnosisItemById(id);
    }
    return 1;
  }

}
